package objaction;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

import org.apache.commons.io.IOUtils;

public class EmbededLGWLSupport {
	private static File createTempDirectory() throws IOException {
		File temp = File.createTempFile("temp", String.valueOf(System.nanoTime()));

		if (!(temp.delete())) {
			throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
		}

		if (!(temp.mkdir())) {
			throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
		}

		return temp;
	}

	public static void loadEmbededLGWGL() throws IOException, SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {
		File tempDir = createTempDirectory();
		String[] dllNames = new String[] { "OpenAL64.dll", "OpenAL32.dll", "lwjgl64.dll", "lwjgl.dll" };

		for (String dllName : dllNames) {
			InputStream libStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(dllName);
			File tempFile = new File(tempDir, dllName);
			FileOutputStream outputStream = new FileOutputStream(tempFile);
			IOUtils.copy(libStream, outputStream);
			outputStream.close();
			libStream.close();
			tempFile.deleteOnExit();

		}

		System.setProperty("java.library.path", tempDir.getPath());
		Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
		fieldSysPath.setAccessible(true);
		fieldSysPath.set(null, null);
	}
}
